﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Linq;
using Volo.Abp.AspNetCore.ExceptionHandling;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc.ExceptionHandling;
using Volo.Abp.Modularity;
using Xms.Abp.AspNetCore.Mvc.ExceptionHandling;
using Xms.Abp.Modularity;

namespace Xms.Abp.AspNetCore.Mvc;

[DependsOn(typeof(AbpAspNetCoreMvcModule))]
public class XmsAbpAspNetCoreMvcModule : XmsModule
{
    public override void PostConfigureServices(ServiceConfigurationContext context)
    {
        base.PostConfigureServices(context);
        context.Services.AddMvc(options =>
        {
            options.Filters.ReplaceOne(x => (x as ServiceFilterAttribute)?.ServiceType?.Name == nameof(AbpExceptionFilter), new ServiceFilterAttribute(typeof(XmsExceptionFilter)));
        });

        var temp = context.Services.FirstOrDefault(r => r.ImplementationType == typeof(DefaultExceptionToErrorInfoConverter));
        if (temp != null)
        {
            context.Services.Remove(temp);
        }
        temp = context.Services.FirstOrDefault(r => r.ImplementationType == typeof(XmsExceptionToErrorInfoConverter));
        if (temp == null)
        {
            context.Services.AddTransient<IExceptionToErrorInfoConverter, XmsExceptionToErrorInfoConverter>();
        }
    }
}

